/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import dto_pakinfo.User;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.criterion.Restrictions;

/**
 *
 * @author duonghung1369
 */
public class UserDAO extends BaseDAO<User> {

    public UserDAO(Class<User> clazz) {
        super(clazz);
    }

    /**
     * Check user login valid or invalid.
     * @param username
     * @param password
     * @return an User object if valid login, null otherwise.
     */
    public User checkLogin(String username, String password) throws HibernateException {
        session.beginTransaction();
        Criteria criteria = session.createCriteria(type);
        criteria.add(Restrictions.and(Restrictions.eq("username", username), Restrictions.eq("password", password)));
        Object result = criteria.uniqueResult();
        return (result != null) ? (User) result : null;
    }

    public boolean register(User user) throws HibernateException {
        session.beginTransaction();
        Criteria criteria = session.createCriteria(type);
        criteria.add(Restrictions.eq("username", user.getUsername()));
        Object obj = criteria.uniqueResult();

        // already registered
        if (obj != null) {
            return false;
        }

        session.save(user.getProfile());
        session.getTransaction().commit();
        return true;
    }

    public boolean deleteUser(int id) {
        boolean result = false;
        session.beginTransaction();
        Criteria criteria = session.createCriteria(type);
        criteria.add(Restrictions.eq("id", id));
        Object obj = criteria.uniqueResult();

        if (obj != null) {
            User user = (User) obj;
            if (user.isIsDeleted()) {
                user.setIsDeleted(false);
            } else {
                user.setIsDeleted(true);
            }



            session.save(user);
            session.getTransaction().commit();
            result = true;
        }
        return result;
    }

    public boolean updateUser(User updatedUser) {
        boolean result = false;
        session.beginTransaction();

        Object obj = get(updatedUser.getId());

        if (obj != null) {
            User user = (User) obj;
            user.setIsAdmin(updatedUser.isIsAdmin());
            //user.setIsDeleted(updatedUser.isIsDeleted());
            user.getProfile().setFirstname(updatedUser.getProfile().getFirstname());
            user.getProfile().setLastname(updatedUser.getProfile().getLastname());
            user.getProfile().setAddress(updatedUser.getProfile().getAddress());
            user.getProfile().setEmail(updatedUser.getProfile().getPhoneNumber());
            user.getProfile().setEmail(updatedUser.getProfile().getEmail());

            session.save(user);
            result = true;
        }
        session.getTransaction().commit();
        return result;
    }
}
